﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using MyLib;

namespace Portal
{
    public partial class SelectUser : System.Web.UI.Page
    {
        private StringBuilder StrSQL;
        public string SelectType = "1";
        private List<string> DepartmentsList;
        private DataTable SelectedTable = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            UserTreeView.ShowExpandCollapse = true;
            UserTreeView.ShowLines = true;
            if (Request.QueryString["Type"] != null)
            {
                SelectType = Request.QueryString["Type"].ToString().Trim();
            }
            if (SelectType == "2")
            {
                Button1.Visible = true;
                Button2.Visible = true;
                SelectedList.Visible = true;
            }
            else
            {
                Button1.Visible = false;
                Button2.Visible = false;
            }
            if (selectTyep.Value.StartsWith("3"))
            {
                UserTreeView.ShowCheckBoxes = TreeNodeTypes.Leaf | TreeNodeTypes.Parent;
            }
            if (!IsPostBack)
            {
                selectTyep.Value = this.SelectType;
                InitTable();
                BingDepartments();
            }
            
        }

        private void BingDepartments()
        {
            StrSQL = new StringBuilder();
            StrSQL.AppendLine("select departmentid,departmentname,parentid  parentdept from V_DEPARTMENT  vt where parentid=0");
            //StrSQL.AppendLine("select id,name,parentdept from V_DEPARTMENT where parentid=0");
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                TreeNode node = new TreeNode();
                //string UserCount = GetUsers(row["departmentid"].ToString().Trim()).ToString();
                node.Text = getDeptName(row["departmentname"].ToString().Trim());// +"[" + UserCount + "]";
                node.Value = row["departmentid"].ToString().Trim() + "~" + row["parentdept"].ToString().Trim();
                
                UserTreeView.Nodes.Add(node);
                if (i == 0)
                {
                    BingFirstNodes(node);
                }
                i++;
            }
        }

        protected void UserTreeView_SelectedNodeChanged(object sender, EventArgs e)
        {
            BingChildNodes();
            BingUserList();
        }

        private void BingFirstNodes(TreeNode nn)
        {
            string nodeValue = nn.Value;
            string id = "";
            string parentdept = "";
            if (nodeValue.IndexOf("~") > 0)
            {
                id = nodeValue.Split('~')[0].ToString().Trim();
                parentdept = nodeValue.Split('~')[1].ToString().Trim();
            }
            StrSQL = new StringBuilder();
            //StrSQL.AppendFormat("select departmentid,departmentname,(select departmentid from V_DEPARTMENT where departmentid=vt.parentid)  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            StrSQL.AppendFormat("select departmentid,departmentname,parentid as  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            if (dt.Rows.Count > 0)
            {
                if (nn.ChildNodes.Count > 0)
                {
                    nn.ChildNodes.Clear();
                }
                foreach (DataRow row in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    //string UserCount = GetUsers(row["departmentid"].ToString().Trim()).ToString();
                    node.Text = getDeptName(row["departmentname"].ToString().Trim());// +"[" + UserCount + "]";
                    node.Value = row["departmentid"].ToString().Trim() + "~" + row["parentdept"].ToString().Trim();
                    nn.ChildNodes.Add(node);
                }
                nn.Expand();
            }
        }

        private void BingChildNodes()
        {
            string nodeValue = UserTreeView.SelectedNode.Value;
            string id = "";
            string parentdept = "";
            if (nodeValue.IndexOf("~") > 0)
            {
                id = nodeValue.Split('~')[0].ToString().Trim();
                parentdept = nodeValue.Split('~')[1].ToString().Trim();
            }
            StrSQL = new StringBuilder();
            //StrSQL.AppendFormat("select departmentid,departmentname,(select departmentid from V_DEPARTMENT where departmentid=vt.parentid)  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            StrSQL.AppendFormat("select departmentid,departmentname,parentid as  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            if (dt.Rows.Count > 0)
            {
                if (UserTreeView.SelectedNode.ChildNodes.Count > 0)
                {
                    UserTreeView.SelectedNode.ChildNodes.Clear();
                }
                foreach (DataRow row in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    //string UserCount = GetUsers(row["departmentid"].ToString().Trim()).ToString();
                    node.Text = getDeptName(row["departmentname"].ToString().Trim());// +"[" + UserCount + "]";
                    node.Value = row["departmentid"].ToString().Trim() + "~" + row["parentdept"].ToString().Trim();
                    UserTreeView.SelectedNode.ChildNodes.Add(node);
                }
                UserTreeView.SelectedNode.Expand();
            }
        }

        private string getDeptName(string name) {
            if (!String.IsNullOrEmpty(name))
            {
                int index = name.IndexOf('[');
                if (index > 0)
                {
                    return name.Substring(0, index);
                }
                else
                {
                    return name;
                }
            }
            else {
                return "";
            }
        }

        private void BingUserList()
        {
            string nodeValue = UserTreeView.SelectedNode.Value;
            string id = "";
            string parentdept = "";
            if (nodeValue.IndexOf('~') > 0)
            {
                id = nodeValue.Split('~')[0].ToString().Trim();
                parentdept = nodeValue.Split('~')[1].ToString().Trim();
            }
            StrSQL = new StringBuilder();
            
            StrSQL.AppendFormat("select ve.EmployeeID,ve.Title,ve.ShortName,ve.FirstName,ve.email  as email from v_empdepartments ved inner join v_employee ve on ved.employeeid=ve.EmployeeID where ved.DepartmentID='{0}'", id);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            Repeater1.DataSource = dt.DefaultView;
            Repeater1.DataBind();
        }

        private decimal GetUsers(string DepartmentID)
        {
            DepartmentsList = new List<string>();
            GetDepartments(DepartmentID);
            decimal UserCount = 0;
            StrSQL = new StringBuilder();
            if (DepartmentsList.Count > 0)
            {
                StrSQL.AppendLine("select count(*) from v_empdepartments ved inner join v_employee ve on ved.employeeid=ve.EmployeeID where ved.DepartmentID in (");
                foreach (string str in DepartmentsList)
                {
                    StrSQL.AppendLine("'" + str + "',");
                }
                StrSQL = new StringBuilder(StrSQL.ToString().Substring(0, StrSQL.ToString().LastIndexOf(',')));
                StrSQL.AppendLine(")");
            }
            else
            {
                StrSQL.AppendLine("select count(*) from v_empdepartments ved inner join v_employee ve on ved.employeeid=ve.EmployeeID where ved.DepartmentID='" + DepartmentID + "'");
            }
            UserCount = DataAccess.Instance("BizDB").ExecuteScalar<decimal>(StrSQL.ToString());
               
            
            return UserCount;
        }

        private void GetDepartments(string DepartmentID)
        {
            StrSQL = new StringBuilder();
            StrSQL.AppendLine("select * from V_DEPARTMENT   where parentid= '" + DepartmentID + "'");
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            foreach (DataRow row in dt.Rows)
            {
                DepartmentsList.Add(row["departmentid"].ToString());
                GetDepartments(row["departmentid"].ToString());
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable dt = ViewState["table"] as DataTable;
            foreach (RepeaterItem item in Repeater1.Items)
            {
                CheckBox cb = item.FindControl("CheckBox1") as CheckBox;
                if (cb.Checked)
                {
                    cb.Enabled = false;
                    string str=(item.FindControl("UserID") as HiddenField).Value;
                    if (dt.Select("EmployeeID="+str).Length == 0)
                    {
                        dt.Rows.Add(dt.NewRow());
                        dt.Rows[dt.Rows.Count - 1]["Title"] = (item.FindControl("Label2") as Label).Text;
                        dt.Rows[dt.Rows.Count - 1]["ShortName"] = (item.FindControl("UserAccount") as HiddenField).Value;
                        dt.Rows[dt.Rows.Count - 1]["FirstName"] = (item.FindControl("Label1") as Label).Text;
                        dt.Rows[dt.Rows.Count - 1]["email"] = (item.FindControl("Label3") as Label).Text;
                        dt.Rows[dt.Rows.Count - 1]["EmployeeID"] = (item.FindControl("UserID") as HiddenField).Value;
                    }
                }
            }
            Repeater2.DataSource = dt;
            Repeater2.DataBind();
            ViewState["table"] = dt;
        }

        private void InitTable()
        {
            this.SelectedTable.Columns.Add("EmployeeID");
            this.SelectedTable.Columns.Add("Title");
            this.SelectedTable.Columns.Add("ShortName");
            this.SelectedTable.Columns.Add("FirstName");
            this.SelectedTable.Columns.Add("email");
            ViewState["table"] = this.SelectedTable;
        }

        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (this.SelectType == "1")
            {
                (e.Item.FindControl("CheckBox1") as CheckBox).Visible = false;
            }
            else if (this.SelectType == "2")
            {
                (e.Item.FindControl("RadioButton1") as RadioButton).Visible = false;
                DataTable dt = ViewState["table"] as DataTable;
                foreach (DataRow row in dt.Rows)
                {
                    if (row["EmployeeID"].ToString() == (e.Item.FindControl("UserID") as HiddenField).Value)
                    {
                        (e.Item.FindControl("CheckBox1") as CheckBox).Checked = true;
                        (e.Item.FindControl("CheckBox1") as CheckBox).Enabled = false;
                    }
                }
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in Repeater2.Items)
            {
                if ((item.FindControl("CheckBox2") as CheckBox).Checked)
                {
                    string id = (item.FindControl("UserID") as HiddenField).Value;
                    DataTable dt = ViewState["table"] as DataTable;
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["EmployeeID"].ToString() == id)
                        {
                            row.Delete();
                            break;
                        }
                    }
                }
            }
            DataTable table = ViewState["table"] as DataTable;
            Repeater2.DataSource = table;
            Repeater2.DataBind();
            foreach (RepeaterItem item in Repeater1.Items)
            {
                CheckBox cb = item.FindControl("CheckBox1") as CheckBox;
                if (cb.Checked)
                {
                    cb.Enabled = false;
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //string nodeValue = UserTreeView.SelectedNode.Value;
            //string id = "";
            //string parentdept = "";
            //if (nodeValue.IndexOf('~') > 0)
            //{
            //    id = nodeValue.Split('~')[0].ToString().Trim();
            //    parentdept = nodeValue.Split('~')[1].ToString().Trim();
            //}
            if (!string.IsNullOrEmpty(txtSearch.Text))
            {
                StrSQL = new StringBuilder();

                StrSQL.AppendFormat("select ve.EmployeeID,ve.Title,ve.ShortName,ve.FirstName,ve.email  as email from   v_employee ve where title like '%{0}%' or firstname like '%{0}%' or shortname like '%{0}%' or email like '%{0}%'", txtSearch.Text.Trim());
                DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
                Repeater1.DataSource = dt.DefaultView;
                Repeater1.DataBind();
            }
        }


    }
}